package sessionutil

import (
	"shop/common/log"
	"shop/config"
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"shop/utils/convertutil"
	"shop/utils/jwtutil"
	"strconv"

	"github.com/gin-gonic/gin"
)

func CheckAdminLogin(userId int64) bool {
	return dao.GetRedisCli().HExists(constant.CacheKeySysUserSessionMap, strconv.FormatInt(userId, 10)).Val()
}

func AdminLogout(userId int64) bool {
	return dao.GetRedisCli().HDel(constant.CacheKeySysUserSessionMap, strconv.FormatInt(userId, 10)).Val() == 1
}

func SetSysUserSession(user *entity.SysUser) string {
	token := jwtutil.GenToken(&jwtutil.JwtClaims{
		UserId: user.Id,
		ShopId: user.ShopId,
	}, int64(3600*24*30))
	SetSysUserCache(user)
	log.Debugf("[add sysUser session], token=" + token)
	return token
}

func SetSysUserCache(user *entity.SysUser) {
	dao.GetRedisCli().HSet(constant.CacheKeySysUserSessionMap, strconv.FormatInt(user.Id, 10), convertutil.ToJsonString(user))
}

// GetSysUserInfo 获取用户信息
func GetSysUserInfo(userId int64) *entity.SysUser {
	user := GetSysUserInfoFromCache(userId)
	if user != nil && user.Id != 0 {
		return user
	}

	if err := dao.GetDB().Model(user).Where("id", userId).Take(user).Error; err != nil {
		log.Errorf("fail to search user from db, err: %v", err)
		return user
	}
	// 拉取权限信息
	user.PermissionSet = map[string]interface{}{}
	user.ParseRoleList()
	for _, roleId := range user.RoleIdList {
		role := config.GetSysRoleById(roleId)
		if len(user.RoleNames) > 0 {
			user.RoleNames += ","
		}
		user.RoleNames += role.Name
		for _, permission := range role.Permissions {
			user.PermissionSet[permission] = true
		}
	}
	SetSysUserCache(user)
	return user
}

func GetSysUserInfoFromCache(sysUserId int64) *entity.SysUser {
	user := entity.SysUser{}
	data := dao.GetRedisCli().HGet(constant.CacheKeySysUserSessionMap, strconv.FormatInt(sysUserId, 10)).Val()
	convertutil.ParseJson(data, &user)
	return &user
}

// GetSysUserIdFromCtx see midware.Auth() and jwtutil.JwtClaims
func GetSysUserIdFromCtx(ctx *gin.Context) int64 {
	return ctx.GetInt64(constant.ParamSysUserId)
}
